<template>
  <div class="admin-login">
    <div class="login-container">
      <div class="login-header">
        <img src="@/assets/jiang.jpg" alt="Logo" class="logo">
        <h2>平台后台管理系统</h2>
      </div>
      <el-form 
        ref="loginFormRef" 
        :model="loginForm" 
        :rules="loginRules" 
        class="login-form" 
        label-position="top"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入管理员用户名" 
            prefix-icon="User"
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码" 
            prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <div class="captcha-container">
            <el-input 
              v-model="loginForm.captcha" 
              placeholder="请输入验证码" 
              prefix-icon="Key"
              @keyup.enter="handleLogin"
            />
            <div class="captcha-image" @click="refreshCaptcha">
              <canvas ref="captchaCanvas" width="120" height="40"></canvas>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading" 
            class="login-button" 
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      <div class="login-footer">
        <p>© {{ new Date().getFullYear() }} 匠心电商平台 版权所有</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAdminStore } from '@/stores/modules/admin'

const router = useRouter()
const route = useRoute()
const adminStore = useAdminStore()

const loginFormRef = ref(null)
const captchaCanvas = ref(null)
const loading = ref(false)
const captchaText = ref('')

const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6到20个字符之间', trigger: 'blur' }
  ],
  captcha: [
  { required: true, message: '请输入验证码', trigger: 'blur' },
  { 
    validator: (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入验证码'))
      } else if (value.toLowerCase() !== captchaText.value.toLowerCase()) {
        callback(new Error('验证码不正确'))
      } else {
        callback()
      }
    }, 
    trigger: 'blur' 
  }
]
}

// 生成随机验证码
const generateCaptcha = () => {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let result = ''
  for (let i = 0; i < 4; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

// 绘制验证码
const drawCaptcha = () => {
  if (!captchaCanvas.value) return
  
  const ctx = captchaCanvas.value.getContext('2d')
  const width = captchaCanvas.value.width
  const height = captchaCanvas.value.height
  
  // 生成新的验证码
  captchaText.value = generateCaptcha()
  
  // 清空画布
  ctx.clearRect(0, 0, width, height)
  
  // 设置背景
  ctx.fillStyle = '#f5f7fa'
  ctx.fillRect(0, 0, width, height)
  
  // 绘制文字
  ctx.font = 'bold 24px Arial'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  
  // 为每个字符设置随机颜色和位置
  for (let i = 0; i < captchaText.value.length; i++) {
    ctx.fillStyle = `rgb(${Math.floor(Math.random() * 150)}, ${Math.floor(Math.random() * 150)}, ${Math.floor(Math.random() * 150)})`
    ctx.save()
    ctx.translate(30 * i + 20, 20)
    ctx.rotate((Math.random() - 0.5) * 0.3)
    ctx.fillText(captchaText.value[i], 0, 0)
    ctx.restore()
  }
  
  // 添加干扰线
  for (let i = 0; i < 5; i++) {
    ctx.strokeStyle = `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 0.5)`
    ctx.beginPath()
    ctx.moveTo(Math.random() * width, Math.random() * height)
    ctx.lineTo(Math.random() * width, Math.random() * height)
    ctx.stroke()
  }
  
  // 添加干扰点
  for (let i = 0; i < 50; i++) {
    ctx.fillStyle = `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 0.5)`
    ctx.beginPath()
    ctx.arc(Math.random() * width, Math.random() * height, 1, 0, 2 * Math.PI)
    ctx.fill()
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  drawCaptcha()
  loginForm.captcha = '' // 清空输入框
}

const handleLogin = async () => {
  if (!loginFormRef.value) {
    console.error('loginFormRef is null')
    return
  }
  
  try {
    console.log('开始表单验证...')
    
    // 表单验证
    await loginFormRef.value.validate()
    console.log('表单验证通过')
    
    loading.value = true
    console.log('开始登录请求...')
    
    // 调用管理员登录API并保存登录状态
    await adminStore.login({
      username: loginForm.username,
      password: loginForm.password
    })
    
    console.log('登录成功')
    ElMessage.success('登录成功')
    
    // 重定向到来源页面或默认页面
    const redirectPath = route.query.redirect || '/jiang/dashboard'
    router.push(redirectPath)
    
  } catch (error) {
    console.error('登录失败:', error)
    // 更详细的错误信息
    if (error.errors) {
      console.error('验证错误详情:', error.errors)
    }
    ElMessage.error(error?.message || '登录失败，请检查用户名和密码')
    refreshCaptcha() // 登录失败时刷新验证码
  } finally {
    loading.value = false
    console.log('登录流程结束')
  }
}

onMounted(() => {
  // 检查是否已登录
  if (adminStore.accessToken && adminStore.adminInfo) {
    router.push('/jiang/dashboard')
  } else {
    // 生成初始验证码
    drawCaptcha()
  }
})
</script>

<style scoped>
.admin-login {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.login-container {
  width: 400px;
  padding: 40px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 15px;
}

.login-header h2 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.login-form {
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
}

.login-footer {
  text-align: center;
  color: #909399;
  font-size: 12px;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-image {
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  height: 40px;
  flex-shrink: 0;
  width: 120px;
}

.captcha-image canvas {
  display: block;
  width: 100%;
  height: 100%;
}
</style>
